import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2023-01-04
 * Time: 下午 19:45
 */

//要对应前端传回来Body格式以及要保证类中的成员变量名称要和前端的Key值相对应
//也要保证类中的属性的权限要是public的,或者提供public的方法
class Message {

    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

//这里的注解就是约定的二级目录名称
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    //private List<Message> list = new ArrayList<>();

    //客服端提交数据给服务器
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //把body里的json数据解析出来
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        //把解析出来的数据进行保存
        //list.add(message);
        save(message);
        System.out.println("message: "+ message);
        //对网页进行响应
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write("{ \"ok\": 1 }");
    }

    //从服务器获取数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");

        List<Message> messageList = load();
        String strMessage = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(strMessage);
    }

    //注意上面两个方法Get是用来获取数据,而Post是用来提交数据,
    //但这都不是一定的,是约定俗成的,也就是说get和post方法可以功能调转着使用(get变成提交数据,post变成获取数据)

    private void save(Message message) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //建立链接
            connection = DBUtil.getConnection();
            //构建语句
            String sql = "insert into MessageWall values(?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, message.from);
            statement.setString(2, message.to);
            statement.setString(3, message.message);
            //执行sql语句
            //每次只添加一行,返回的ret表示影响了几行,也就是修改了几行,只要等于1才是正常插入,其他则插入错误
            int ret = statement.executeUpdate();
            if(ret != 1) {
                System.out.println("插入失败!");
            }else {
                System.out.println("插入成功!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭连接
            DBUtil.close(connection,statement,null);
        }


    }

    private List<Message> load() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Message> list = new ArrayList<>();

        try {
            //建立连接
            connection = DBUtil.getConnection();
            //构建语句
            String sql = "select * from MessageWall";
            statement = connection.prepareStatement(sql);

            //执行sql语句
            resultSet = statement.executeQuery();

            //打印临时表
            while(resultSet.next()) {
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                list.add(message);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,resultSet);
        }

        return list;
    }
}
